﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DomainModel.PDC;

namespace Infrastructure.DC
{
    public class CustomersDao : Infrastructure.DC.ICustomersDao
    {
        public CustomersDao()
        {

        }

        public IEnumerable<Customer> RetrieveAll()
        {
           return FakeDatabase.Current.Customers.ToList();
        }

        public int Save(Customer customer)
        {
            return FakeDatabase.Current.AddCustomer(customer);
        }


        public Customer RetrieveById(int id)
        {
            return FakeDatabase.Current.Customers.SingleOrDefault(c => c.CustomerId == id);
        }


        public void Update(Customer customer)
        {
            var cust= FakeDatabase.Current.Customers.SingleOrDefault(c => c.CustomerId == customer.CustomerId);
            cust.FirstName = customer.FirstName;
            cust.LastName = customer.LastName;
        }


        public void RemoveById(int id)
        {
          
            FakeDatabase.Current.RemoveCustomer(id);
        }
    }


    internal class FakeDatabase
    {
        private static FakeDatabase _database;
        private readonly List<Customer> _customers;
        internal static FakeDatabase Current
        {
            get
            {
                if (_database == null)
                {
                    _database = new FakeDatabase();
                }
                return _database;
            }
        }
        private FakeDatabase()
        {

            _customers =  new List<Customer>
            {
                new Customer { CustomerId =1 , FirstName="Alice", LastName="Brown"},
                 new Customer { CustomerId =2 , FirstName="Bob", LastName="Dewey"},
                      new Customer { CustomerId =3 , FirstName="Charlie", LastName="Esner"}
         
            };

        }

        public IEnumerable<Customer> Customers { get { return _customers; } }
        public int AddCustomer(Customer customer)
        {
            var topId = _customers.Max(c => c.CustomerId);
            customer.CustomerId = topId + 1;
            _customers.Add(customer);
            return customer.CustomerId;
        }
        public void RemoveCustomer(int id)
        {
            var cust =_customers.SingleOrDefault(c => c.CustomerId == id);
            if (cust != null)
            {
                _customers.Remove(cust);
            }
        }
    }
}
